# -*- encoding=utf8 -*-
import subprocess
import time


class ADBHelper:
    # __init__方法是一个特殊的方法，‌用于初始化新创建的对象属性
    # 确保了每当一个新的对象被创建时，‌其属性都能被正确地初始化和设置
    def __init__(self):
        # 确保ADB服务器正在运行
        self.start_adb_server()

    #  启动ADB服务器
    def start_adb_server(self):
        try:
            # 启动ADB服务器
            command = ['adb', 'start-server']
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            print("ADB服务器启动成功:", result.stdout)
        except subprocess.CalledProcessError as e:
            print("ADB服务器启动失败:", e.stderr)

    # 检查已连接的设备
    def check_connected_devices(self):
        try:
            # 检查已连接的设备
            command = ['adb', 'devices']
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            print("已连接的设备:")
            print(result.stdout)
            return result.stdout
        except subprocess.CalledProcessError as e:
            print("检查设备失败:", e.stderr)
            return None

    # 连接设备
    def connect_device(self, ip_port):
        try:
            command = ['adb', 'connect', ip_port]
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            print("连接设备结果:", result.stdout)
            return result.stdout
        except subprocess.CalledProcessError as e:
            print("连接设备失败:", e.stderr)
            return None

    #  安装apk
    def install_apk(self, apk_path, device_serial=None):
        try:
            # 构建ADB安装命令
            start = time.time()
            command = ['adb'] + (['-s', device_serial] if device_serial else []) + ['install', apk_path]
            end = time.time()
            # 执行命令
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            # 输出结果
            print("安装成功:    共计耗时{0}".format(end - start))
            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print("安装失败:")
            print(e.stderr)

    #  检查apk的安装
    def check_app_installed(self, package_name, device_serial=None):
        try:
            # 构建ADB安装命令
            command = ['adb'] + (['-s', device_serial] if device_serial else []) + ['shell', 'pm', 'list', 'packages',
                                                                                    '-3']
            # 执行命令
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            # 检查包名是否在输出中
            if package_name in result.stdout:
                print("包名已安装")
                print(result.stdout)
            else:
                print("包名未安装")
                print(result.stdout)
            return package_name in result.stdout
        except subprocess.CalledProcessError as e:
            print("检查安装失败:", e.stderr)

    #  卸载apk
    def uninstall_apk(self, package_name, device_serial=None):
        try:
            # 构建ADB安装命令
            command = ['adb'] + (['-s', device_serial] if device_serial else []) + ['uninstall', package_name]
            # 执行命令
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            # 输出结果
            print("卸载成功:", result.stdout)
        except subprocess.CalledProcessError as e:
            print("卸载失败:", e.stderr)

    #  打开apk软件
    def start_app(self, package_name, activity_name=None, device_serial=None):
        """
        启动指定包名的应用程序，如果提供了activity_name，则启动指定的Activity。

        :param package_name: 应用程序的包名
        :param activity_name: 要启动的Activity名称（可选）
        :param device_serial: 设备序列号（可选）
        """
        try:
            # 构建ADB启动命令
            command = ['adb'] + (['-s', device_serial] if device_serial else []) + ['shell', 'am', 'start']
            if activity_name:
                command.extend(['-n', f'{package_name}/{activity_name}'])
            else:
                command.extend(['-n', f'{package_name}/.{package_name.split(".")[-1]}Activity'])  # 尝试默认Activity

            # 执行命令
            result = subprocess.run(command, check=True, capture_output=True, text=True)
            print("启动成功:", result.stdout)
        except subprocess.CalledProcessError as e:
            print("启动失败:", e.stderr)

    #  获取apk的activity
    def get_app_info_from_apk(self, apk_path):
        """
        使用 aapt 解析 APK 文件并返回应用的详细信息。

        :param apk_path: APK 文件路径
        :return: 包含应用详细信息的字典
        """
        try:
            # 构建 aapt 命令
            command = ['aapt', 'dump', 'badging', apk_path]
            result = subprocess.run(command, check=True, capture_output=True, text=True)

            app_info = {}
            for line in result.stdout.splitlines():
                if line.startswith('package:'):
                    package_info = line.split()
                    for item in package_info:
                        if item.startswith('name='):
                            app_info['package_name'] = item.split('\'')[1]
                        elif 'versionCode=' in item:
                            app_info['version_code'] = item.split('\'')[1]
                        elif 'versionName=' in item:
                            app_info['version_name'] = item.split('\'')[1]
                elif line.startswith('application-label:'):
                    app_info['label'] = line.split(':')[1].strip()
                elif line.startswith('sdkVersion:'):
                    app_info['min_sdk_version'] = line.split(':')[1].strip()
                elif line.startswith('targetSdkVersion:'):
                    app_info['target_sdk_version'] = line.split(':')[1].strip()
                # elif 'uses-permission:' in line:
                #     permission = line.split('\'')[1]
                #     if 'permissions' not in app_info:
                #         app_info['permissions'] = []
                #     app_info['permissions'].append(permission)
                elif 'activity:' in line:
                    activity = line.split('\'')[1]
                    if 'activities' not in app_info:
                        app_info['activities'] = []
                    app_info['activities'].append(activity)

            return app_info
        except subprocess.CalledProcessError as e:
            print("解析 APK 失败:", e.stderr)
            return None


if __name__ == '__main__':
    apk_path = "/Users/wancongpeng/Downloads/apk/cloudphone.apk"
    package_name = "com.ss.android.ugc.aweme"
    activity_name = 'com.ss.android.ugc.aweme.splash.SplashActivity'
    device_serial = '60.28.168.125:20446'  # 替换为实际设备序列号

    adbhelper = ADBHelper()
    # adbhelper.check_connected_devices()
    # adbhelper.connect_device(device_serial)
    # adbhelper.check_connected_devices()
    # adbhelper.install_apk(apk_path, device_serial=device_serial)
    # adbhelper.check_app_installed(package_name, device_serial=device_serial)
    # adbhelper.start_app(package_name, activity_name=activity_name, device_serial=device_serial)
    app_info =adbhelper.get_app_info_from_apk(apk_path)
    print(app_info)


